package com.webserver.http;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 请求对象，该类的每一个实例用于标识HTTP协议规定的请求内容
 * 一个请求由三部分构成:
 * 1:请求行
 * 2:消息头
 * 3:消息正文
 * @author XingHaiYang
 * @date 2022/9/17 17:48
 */
public class HttpServletRequest {
    /**
     * 定义s对象，请求行的内容分三部分，消息头
     */
    private Socket s;
    private String method;
    private String uri;
    private String protocol;
    private Map<String,String> headers = new HashMap<>();
    private Map<String,String> parameters = new HashMap<>();//每一组参数
    private String requestURI;//uri中的请求部分，即:"?"左侧内容
    private String queryString;//uri中的参数部分，即:"?"右侧内容

    /**
     * 构造器，给s赋值
     * @param s
     */
    public HttpServletRequest(Socket s) throws IOException, EmptyRequestException {
        this.s = s;
        //1解析请求行
        parseRequestLine();
        //2解析消息头
        parseHeaders();
        //3解析消息正文
        parseContent();
    }

    /**
     * 解析消息正文
     */
    private void parseContent() {

    }

    /**
     * 解析消息头
     */
    private void parseHeaders() throws IOException {
        //读取消息头
        while (true){
            String line = readLine();
            if(line.isEmpty()){
                break;
            }
            System.out.println("消息头为："+line);
            String[] data = line.split("\\s");
            headers.put(data[0],data[1]);
        }
        System.out.println("headers:"+headers);
    }

    /**
     * 解析请求行
     * @throws IOException
     */
    private void parseRequestLine() throws IOException, EmptyRequestException {
        // 读取请求行
        String line = readLine();
        if(line.isEmpty()){ //若请求行为空字符串
            throw new EmptyRequestException();//抛出空请求异常
        }
        String[] data = line.split("\\s");
        method = data[0];
        uri = data[1];
        protocol = data[2];
        //进一步解析uri
        parseURI();
        System.out.println("method:"+method);
        System.out.println("uri:"+uri);
        System.out.println("protocol:"+protocol);
    }

    private void parseURI() {
        String[] data = uri.split("\\?");
        requestURI = data[0];
        if(data.length>1){
            queryString = data[1];
            //对参数部分进行转码
            try {
                queryString = URLDecoder.decode(queryString,"UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            data = queryString.split("&");
            for (String para : data) {
                String[] arr = para.split("=", 2);
                parameters.put(arr[0],arr[1]);
            }
        }
        System.out.println("requestURI:"+requestURI);
        System.out.println("queryString:"+queryString);
        System.out.println("parameters:"+parameters);
    }

    /**
     * 服务器听,读取请求内容
     */
    public String readLine() throws IOException {
        //服务端主动听
        InputStream in = s.getInputStream();
            /*InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
            BufferedReader br = new BufferedReader(isr);
            String listen;
            while((listen = br.readLine()) != null){
                System.out.println("客户端说："+listen);
            }*/
        StringBuilder sb = new StringBuilder();
        char pre='a',cur='a';
        int listen;
        while ((listen=in.read()) != -1){
            cur = (char)listen;
            if(pre==13 && cur==10){
                break;
            }
            sb.append(cur);
            pre = cur;
        }
        String line = sb.toString().trim();
        System.out.println("请求行内容："+line);
        return line;
    }

    /**
     * 生成get方法，方便外界调用
     * @return
     */
    public String getMethod() {
        return method;
    }

    public String getUri() {
        return uri;
    }

    public String getProtocol() {
        return protocol;
    }

    /**
     * 根据消息头的名字获取对应的值
     * @param name
     * @return
     */
    public String getHeader(String name) {
        return headers.get(name);
    }

    public String getParameter(String name) {
        return parameters.get(name);
    }
}
